from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Static, Button
from textual.binding import Binding

from ..dialogs import InformationDialog, HelpDialog
from ..screens import MainScreen, PackagesScreen
from ..data import load_config, save_config

class SparkStoreApp(App):
    ''' 基于 Textual 的星火应用商店终端版 App '''

    # 定义 键 绑定
    BINDINGS = [
        Binding('q', 'quit', '退出(Quit)'),
        Binding('b', 'about', '关于(About)'),
        Binding('?', 'help', '帮助(Help)'),
        Binding('t', 'toggle_theme', '切换主题(Toggle Theme)'),
        Binding('m', "app.switch_mode('main')", '主页(Main)'),
        Binding('p', "app.switch_mode('packages')", '应用列表(Packages)'),
    ]

    # 默认显示模式
    DEFAULT_MODE = 'main'

    # 应用显示模式
    MODES = {
        'main': MainScreen,
        'packages': PackagesScreen,
    }

    def compose(self) -> ComposeResult:
        yield Header(show_clock=True)
        yield Footer()

    def on_mount(self) -> None:
        '''挂载时，设置主题'''
        self.theme = load_config().theme

    def action_about(self):
        '''动作，显示关于(About)界面'''
        SPARK_STORE_PROJECT = 'https://gitee.com/spark-store-project'
        SPARK_STORE_LICENSE = 'https://gitee.com/spark-store-project/spark-store/blob/Flamescion/LICENSE'
        self.push_screen(
            InformationDialog(
                "关于(About)", 
                f"主页：[@click=app.visit('{SPARK_STORE_PROJECT}')]星火计划[/] \n\n"
                f"描述：一款由社区提供的应用商店\n\n"
                f"鸣谢：致谢所使用的开源软件\n\n"
                f"License: 星火应用商店遵循 [@click=app.visit('{SPARK_STORE_LICENSE}')]Spark Opensource License[/] 协议"
            )
        )

    def action_help(self):
        '''动作，显示帮助(Help)界面'''
        self.push_screen(HelpDialog())
        
    def action_toggle_theme(self) -> None:
        '''动作，切换主题(Toggle Theme)'''
        self.theme = (
            "textual-dark" if self.theme == "textual-light" else "textual-light"
        )
        
        config = load_config()
        config.theme = self.theme
        save_config(config)

def runApp():
    app = SparkStoreApp()
    app.title = '星火应用商店(Spak Store)'.title()
    app.sub_title = "终端版(based on Textual)"
    app.run()


if __name__ == "__main__":
    runApp()

